<template>
  <div class="class-stats">
    <div class="stats-summary">
      <span>平均分：{{ avgScore }}</span>
      <span>最高分：{{ maxScore }}</span>
      <span>最低分：{{ minScore }}</span>
      <span>及格率：{{ passRate }}%</span>
      <span>优秀率：{{ excellentRate }}%</span>
    </div>
    <div ref="chartRef" class="chart"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, computed } from 'vue'
import * as echarts from 'echarts'

const props = defineProps({
  scores: {
    type: Array,
    default: () => []
  }
})

const chartRef = ref(null)

const allScores = computed(() => props.scores.map(s => s.score || 0))
const avgScore = computed(() => {
  if (!allScores.value.length) return '-'
  const sum = allScores.value.reduce((acc, cur) => acc + cur, 0)
  return (sum / allScores.value.length).toFixed(2)
})
const maxScore = computed(() => {
  if (!allScores.value.length) return '-'
  return Math.max(...allScores.value)
})
const minScore = computed(() => {
  if (!allScores.value.length) return '-'
  return Math.min(...allScores.value)
})
const passRate = computed(() => {
  if (!allScores.value.length) return '-'
  const pass = allScores.value.filter(s => s >= 60).length
  return ((pass / allScores.value.length) * 100).toFixed(1)
})
const excellentRate = computed(() => {
  if (!allScores.value.length) return '-'
  const excellent = allScores.value.filter(s => s >= 90).length
  return ((excellent / allScores.value.length) * 100).toFixed(1)
})

// 课程成绩对比（每门课的平均分）
const courseAvg = computed(() => {
  const map = {}
  props.scores.forEach(s => {
    if (!map[s.courseName]) map[s.courseName] = []
    map[s.courseName].push(s.score || 0)
  })
  return Object.keys(map).map(name => ({
    name,
    avg: (map[name].reduce((a, b) => a + b, 0) / map[name].length).toFixed(2)
  }))
})

const renderChart = () => {
  if (!chartRef.value) return
  const chart = echarts.init(chartRef.value)
  chart.setOption({
    title: { text: '各课程平均分对比', left: 'center', top: 10, textStyle: { fontSize: 16 } },
    tooltip: {},
    xAxis: { type: 'category', data: courseAvg.value.map(c => c.name) },
    yAxis: { type: 'value', min: 0, max: 100 },
    series: [{
      data: courseAvg.value.map(c => c.avg),
      type: 'bar',
      itemStyle: { color: '#67c23a', borderRadius: [6,6,0,0] },
      barWidth: 32
    }]
  })
}

onMounted(() => {
  renderChart()
})
watch(() => props.scores, () => {
  renderChart()
})
</script>

<style scoped>
.class-stats {
  margin-bottom: 24px;
  background: #f8fafc;
  border-radius: 12px;
  padding: 18px 18px 10px 18px;
  box-shadow: 0 2px 8px 0 rgba(103,194,58,0.06);
}
.stats-summary {
  display: flex;
  flex-wrap: wrap;
  gap: 24px;
  font-size: 15px;
  margin-bottom: 12px;
  color: #333;
}
.chart {
  width: 100%;
  min-height: 260px;
  height: 300px;
}
</style> 